<template>
  <div class="ai-paper-generator-box" :class="{ 'fullscreen': !isFullscreen }">
    <!-- 头部导航 -->
    <div class="generator-header">
      <div class="header-left">
        <h2><i class="fas fa-robot"></i> AI智能出卷</h2>
        <div class="mode-tabs">
          <button :class="{ active: activeMode === 'existing' }" @click="activeMode = 'existing'">
            <i class="fas fa-database"></i> 基于题库出卷
          </button>
          <!-- <button :class="{ active: activeMode === 'aiPanel' }" @click="activeMode = 'aiPanel'">
            <i class="fas fa-magic"></i> AI自动组卷
          </button> -->
        </div>
      </div>
      <div class="header-right">
        <button class="btn-icon" @click="toggleFullscreen">
          <i :class="isFullscreen ? 'fas fa-compress' : 'fas fa-expand'"></i>
        </button>
        <!-- <button class="btn-save" @click="savePaper">
          <i class="fas fa-save"></i> 保存试卷
        </button> -->
        <button class="btn-icon btn-close" @click="$emit('close')">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="generator-main">
      <!-- 配置面板 -->
      <div class="config-panel">
        <!-- 基础信息 -->
        <div class="panel-section">
          <h3><i class="fas fa-info-circle"></i> 试卷信息</h3>
          <div class="form-group">
            <label>试卷名称</label>
            <input :class="{ 'paper-name-red': isDuplicatePaperName }" v-model="paperConfig.name" type="text"
              placeholder="例如：2023年Java期末考试">
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>总分(自动调整)</label>
              <input v-model.number="createPaperTotalScore" type="number" min="1" disabled>
            </div>
            <div class="form-group">
              <label>考试时长(分钟)</label>
              <input v-model.number="paperConfig.duration" type="number" min="1">
            </div>
          </div>
        </div>

        <!-- 基于题库组卷配置 -->
        <div class="panel-section" v-if="activeMode === 'existing'">
          <h3><i class="fas fa-database"></i> 题库选择</h3>
          <div class="selected-banks-container">
            <div class="selected-banks">
              <div v-for="bank in selectedBankDetails" :key="bank.questionBank.bankId" class="bank-tag">
                <div class="bank-tag-content">
                  <span class="bank-name">{{ bank.questionBank.bankName }}</span>
                  <span class="question-count">{{ bank.questionBank.totalQuestionNum }}题</span>
                </div>
                <button class="remove-bank" @click.stop="removeBank(bank.questionBank.bankId)">
                  <i class="fas fa-times"></i>
                </button>
              </div>
              <button class="btn-add-bank" @click="showBankModal = true">
                <i class="fas fa-plus"></i> 添加题库
              </button>
            </div>
            <div class="bank-selection-hint" v-if="selectedBanks.length === 0">
              <i class="fas fa-info-circle"></i>
              <span>请添加至少一个题库以继续</span>
            </div>
          </div>
        </div>

        <!-- 题库选择模态框 -->
        <BankSelectionModal v-if="showBankModal" :selected-banks="selectedBanks" :question-banks="questionBanks"
          @close="showBankModal = false" @update-selection="updateBankSelection" />

        <!-- AI生成配置 -->
        <div class="panel-section" v-if="activeMode === 'aiPanel'">
          <h3><i class="fas fa-cogs"></i> AI生成配置</h3>
          <div class="form-group">
            <label>主题/知识点</label>
            <textarea v-model="aiConfig.keywords" placeholder="例如：Java多线程、数据库索引、操作系统进程管理等" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>生成风格</label>
            <select v-model="aiConfig.style">
              <option value="exam">考试风格</option>
              <option value="practice">练习风格</option>
              <option value="conceptual">概念理解</option>
              <option value="simulation">模拟考试</option>
            </select>
          </div>
          <div class="form-group">
            <label>AI智能程度</label>
            <div class="ai-intelligence">
              <input type="range" v-model="aiConfig.intelligence" min="1" max="5" step="1">
              <div class="intensity-labels">
                <span v-for="i in 5" :key="i" :class="{ active: aiConfig.intelligence >= i }">
                  <i class="fas fa-brain"></i>
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 题型配置 -->
        <div class="panel-section">
          <div class="section-header">
            <div class="header-left">
              <i class="fas fa-list-ol" style="margin: 0 0 1rem 0;"></i>
              <h3>题型配置</h3>
            </div>
            <div class="total-count">
              总计: <strong>{{ totalQuestions }}</strong> 题 | 总分: <strong>{{ calculatedTotalScore }}</strong> 分
            </div>
          </div>
          <div class="question-type-config">
            <div v-for="type in questionTypes" :key="type.value" class="type-card"
              :class="{ active: paperConfig.questionTypes[type.value] > 0 }">
              <div class="type-header" @click="toggleQuestionType(type.value)">
                <div class="type-icon" :style="{ backgroundColor: typeColors[type.value] }">
                  <i :class="type.icon"></i>
                </div>
                <div class="type-info">
                  <h4>{{ type.label }}</h4>
                  <p>{{ typeDescriptions[type.value] }}</p>
                </div>
                <!-- <div class="type-badge" v-if="paperConfig.questionTypes[type.value] > 0">
                  {{ paperConfig.questionTypes[type.value] }}题
                </div> -->
              </div>
              <div class="type-controls" v-if="paperConfig.questionTypes[type.value] > 0">
                <div class="type-score-control">
                  <label>每题分数</label>
                  <input v-model.number="typeScores[type.value]" type="number" min="1"
                    @change="validateTypeScore(type.value)">
                </div>
                <div class="type-count-control">
                  <button class="btn-count" @click.stop="adjustTypeCount(type.value, -1)">
                    <i class="fas fa-minus-circle"></i>
                  </button>
                  <span class="count-display">{{ paperConfig.questionTypes[type.value] }}</span>
                  <button class="btn-count" @click.stop="adjustTypeCount(type.value, 1)">
                    <i class="fas fa-plus-circle"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="height: 10px;"></div>
        <!-- 高级选项 -->
        <!-- <div class="panel-section">
          <h3><i class="fas fa-sliders-h"></i> 高级选项</h3>
          <div class="form-group">
            <label>难度分布</label>
            <div class="difficulty-distribution">
              <div
                  v-for="(label, level) in difficultyLevels"
                  :key="level"
                  class="difficulty-item"
              >
                <span>{{ label }}</span>
                <input
                    v-model.number="paperConfig.difficultyDistribution[level]"
                    type="number"
                    min="0"
                    max="100"
                >%
              </div>
            </div>
            <div class="difficulty-preview">
              <div
                  v-for="(label, level) in difficultyLevels"
                  :key="level"
                  class="difficulty-bar"
                  :style="{ width: `${paperConfig.difficultyDistribution[level]}%`, backgroundColor: difficultyColors[level] }"
                  :title="`${label}: ${paperConfig.difficultyDistribution[level]}%`"
              ></div>
            </div>
          </div>
          <div class="form-group">
            <label>知识点覆盖率</label>
            <div class="coverage-control">
              <input
                  type="range"
                  v-model="paperConfig.coverage"
                  min="30"
                  max="100"
                  step="5"
              >
              <span>{{ paperConfig.coverage }}%</span>
            </div>
          </div>
        </div> -->


      </div>
      <!-- 预览面板 -->
      <div class="preview-panel">
        <div v-if="generating" class="waiting-paper">
          <div class="loader-container">
            <div class="paper-loader"></div>
            <p>{{ currentThinkingText }}</p>
            <div class="thinking-dots">
              <div class="dot"></div>
              <div class="dot"></div>
              <div class="dot"></div>
            </div>
            <div class="generation-status">
              <div class="status-title">AI正在思考并组合试卷中...</div>
              <div class="status-list">
                <div class="status-item"
                  :class="{ active: generationProgress === 0, completed: generationProgress > 0 }">
                  <i class="fas" :class="generationProgress > 0 ? 'fa-check-circle' : 'fa-spinner fa-spin'"></i>
                  <span>正在分析题库内容</span>
                </div>
                <div class="status-item"
                  :class="{ active: generationProgress === 1, completed: generationProgress > 1 }">
                  <i class="fas"
                    :class="generationProgress > 1 ? 'fa-check-circle' : (generationProgress === 1 ? 'fa-spinner fa-spin' : 'fa-circle')"></i>
                  <span>正在按照题型筛选题目</span>
                </div>
                <div class="status-item"
                  :class="{ active: generationProgress === 2, completed: generationProgress > 2 }">
                  <i class="fas"
                    :class="generationProgress > 2 ? 'fa-check-circle' : (generationProgress === 2 ? 'fa-spinner fa-spin' : 'fa-circle')"></i>
                  <span>正在计算试卷难度平衡</span>
                </div>
                <div class="status-item"
                  :class="{ active: generationProgress === 3, completed: generationProgress > 3 }">
                  <i class="fas"
                    :class="generationProgress > 3 ? 'fa-check-circle' : (generationProgress === 3 ? 'fa-spinner fa-spin' : 'fa-circle')"></i>
                  <span>正在优化知识点分布</span>
                </div>
                <div class="status-item"
                  :class="{ active: generationProgress === 4, completed: generationProgress > 4 }">
                  <i class="fas"
                    :class="generationProgress > 4 ? 'fa-check-circle' : (generationProgress === 4 ? 'fa-spinner fa-spin' : 'fa-circle')"></i>
                  <span>正在进行最终校验</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else-if="!paperGenerated" class="empty-preview">
          <i class="fas fa-robot ai-robot-icon"></i>
          <h3 class="preview-title">AI智能组卷</h3>
          <p class="preview-desc">完成配置后点击"开始组卷"生成试卷</p>
          <div class="preview-features">
            <div class="feature-item">
              <i class="fas fa-bolt"></i>
              <span>智能匹配题型</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-balance-scale"></i>
              <span>自动平衡难度</span>
            </div>
            <div class="feature-item">
              <i class="fas fa-magic"></i>
              <span>知识点全覆盖</span>
            </div>
          </div>
          <div class="preview-note">
            <i class="fas fa-info-circle"></i>
            <p>AI组卷过程可能需要较长时间，请耐心等待</p>
          </div>
        </div>
        <AipaperGeneratorResultHeader v-else :clickGenerator="false"></AipaperGeneratorResultHeader>
      </div>
    </div>
    <!-- 底部操作按钮 -->
    <div class="action-buttons">
      <button class="btn-generate" @click="generatePaper" :disabled="generating || !canGenerate || paperGenerated">
        <i class="fas" :class="generating ? 'fa-spinner fa-spin' : 'fa-bolt'"></i>
        {{ generating ? 'AI思考中...' : paperGenerated ? '已生成试卷' : '开始组卷' }}
      </button>
      <button class="btn-reset" @click="resetConfig">
        <i class="fas fa-redo"></i> 重置
      </button>
    </div>
  </div>
</template>

<script>
import BankSelectionModal from '@/components/paper/BankSelectionModal.vue'
import AipaperGeneratorResultHeader from './AipaperGeneratorResultHeader.vue'

import { getQuestionBankList as getQuestionBankListAPI, listQuestionBankAndQuestionNum as listQuestionBankAndQuestionNumAPI } from '@/api/question'

import { createPaperWithQuestions as createPaperWithQuestionsAPI } from '@/api/paper'

import { mapGetters } from 'vuex'

export default {
  name: 'AIPaperGeneratorModal',
  props: {
    // bankId: {
    //   type: [String, Number],
    //   required: true
    // }
  },
  components: {
    BankSelectionModal,
    AipaperGeneratorResultHeader
  },
  data() {
    return {
      showBankModal: false,
      isFullscreen: true,
      activeMode: 'existing', // 'existing' or 'aiPanel'
      generating: false,
      paperGenerated: false,
      generationProgress: 0,
      currentThinkingText: '',
      thinkingTexts: [
        '正在分析知识点分布...',
        '正在筛选合适题目...',
        '正在计算难度平衡...',
        '正在优化试卷结构...',
        '正在进行最终校验...'
      ],
      thinkingInterval: null,
      progressTimer: null,
      showAnalysis: {},
      paperConfig: {
        name: '',
        totalScore: 100,
        duration: 90,
        coverage: 70,
        questionTypes: {
          single: 1,
          multiple: 1,
          truefalse: 1,
          fillblank: 1,
          essay: 1
        },
        difficultyDistribution: {
          easy: 20,
          medium: 60,
          hard: 20
        }
      },
      aiConfig: {
        keywords: '',
        style: 'exam',
        intelligence: 3
      },
      selectedBanks: [],
      questionBanks: [
        {
          id: 1,
          name: 'Java基础题库',
          questionCount: 156,
          tags: ['Java', '基础', 'OOP']
        },
        {
          id: 2,
          name: '数据库系统题库',
          questionCount: 89,
          tags: ['SQL', 'NoSQL', '事务']
        },
        {
          id: 3,
          name: '操作系统题库',
          questionCount: 112,
          tags: ['进程', '内存', '文件']
        },
        {
          id: 4,
          name: '计算机网络题库',
          questionCount: 78,
          tags: ['TCP/IP', 'HTTP', '安全']
        }
      ],
      questionTypes: [
        { value: 'single', label: '单选题', icon: 'fas fa-dot-circle' },
        { value: 'multiple', label: '多选题', icon: 'fas fa-check-double' },
        { value: 'truefalse', label: '判断题', icon: 'fas fa-balance-scale' },
        { value: 'fillblank', label: '填空题', icon: 'fas fa-pencil-alt' },
        { value: 'essay', label: '简答题', icon: 'fas fa-align-left' }
      ],
      typeColors: {
        single: '#4361EE',
        multiple: '#3A0CA3',
        truefalse: '#10B981',
        fillblank: '#F59E0B',
        essay: '#F72585'
      },
      typeScores: {
        single: 5,
        multiple: 8,
        truefalse: 3,
        fillblank: 5,
        essay: 10
      },
      typeDescriptions: {
        single: '选择一个正确答案',
        multiple: '选择多个正确答案',
        truefalse: '判断陈述是否正确',
        fillblank: '填写空白处的答案',
        essay: '简要回答题目问题'
      },
      difficultyLevels: {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      },
      difficultyColors: {
        easy: '#10B981',
        medium: '#F59E0B',
        hard: '#EF4444'
      },
      generatedPaper: [],
    }
  },
  computed: {
    ...mapGetters('question', ['banks']),
    ...mapGetters('paper', [
      'getPaperQuestions', // 从 Vuex 中获取 paperQuestions
      'getGeneratePaperId',
      'getPapers'
    ]),
    // 生成的id
    generatePaperId: {
      get() {
        return this.getGeneratePaperId; // 绑定到 Vuex 的 getter
      },
      set(value) {
        this.$store.commit('paper/setGeneratePaperId', value); // 绑定到 Vuex 的 setter
      }
    },
    // 试卷题目
    paperQuestions: {
      get() {
        return this.getPaperQuestions; // 绑定到 Vuex 的 getter
      },
      set(value) {
        this.$store.commit('paper/setPaperQuestions', value); // 绑定到 Vuex 的 setter
      }
    },
    // 事件列表
    papers: {
      get() {
        return this.getPapers; // 绑定到 Vuex 的 getter
      },
      set(value) {
        this.$store.commit('paper/setPapers', value); // 绑定到 Vuex 的 setter
      }
    },
    question_Banks: {
      get() {
        return this.banks
      },
      set(value) {
        this.$store.commit('question/setBanks', value)
      }
    },
    selectedBankDetails() {
      return this.questionBanks.filter(bank => {
        // 兼容 bankId 和 questionBank.bankId 两种结构
        const id = bank.bankId || (bank.questionBank && bank.questionBank.bankId);
        return this.selectedBanks.includes(id);
      });
    },
    totalQuestions() {
      return Object.values(this.paperConfig.questionTypes).reduce((a, b) => a + b, 0)
    },
    calculatedTotalScore() {
      let total = 0
      for (const type in this.paperConfig.questionTypes) {
        total += this.paperConfig.questionTypes[type] * this.typeScores[type]
      }
      return total
    },
    canGenerate() {
      if (this.activeMode === 'existing') {
        return (
          this.paperConfig.name.trim() !== '' &&
          this.totalQuestions > 0 &&
          this.selectedBanks.length > 0 &&
          this.isDuplicatePaperName == false
        )
      } else {
        return (
          this.paperConfig.name.trim() !== '' &&
          this.totalQuestions > 0 &&
          this.aiConfig.keywords.trim() !== '' &&
          this.isDuplicatePaperName == true
        )
      }
    },
    createPaperTotalScore() {
      let total = 0
      for (const type in this.paperConfig.questionTypes) {
        total += this.paperConfig.questionTypes[type] * this.typeScores[type]
      }
      return total
    },
    isDuplicatePaperName() { // 检查试卷名称是否重复
      return this.papers.some(item => item.paperName === this.paperConfig.name)
    }
  },
  created() {
    this.getQuestionBankList()
    this.startThinkingAnimation()
  },
  methods: {
    async getQuestionBankList() {

      try {
        let res = await listQuestionBankAndQuestionNumAPI();
        let { data } = res.data;
        this.questionBanks = data;
      } catch (error) {
        // console.error('获取题库列表失败:', error);
        this.$message.error('服务器繁忙，请稍后重试');
      }

    },
    removeBank(bankId) {
      this.selectedBanks = this.selectedBanks.filter(id => id !== bankId)
    },
    updateBankSelection(selectedIds) {
      this.selectedBanks = selectedIds
      this.showBankModal = false
    },
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
    },
    savePaper() {
      const paperData = {
        config: this.paperConfig,
        questions: this.generatedPaper,
        createdAt: new Date().toISOString()
      }
      // 这里实际应该调用API保存
      this.$message.success('试卷保存成功！')
    },
    startThinkingAnimation() {
      let index = 0
      this.currentThinkingText = this.thinkingTexts[0]
      this.thinkingInterval = setInterval(() => {
        index = (index + 1) % this.thinkingTexts.length
        this.currentThinkingText = this.thinkingTexts[index]
      }, 2000)
    },
    stopThinkingAnimation() {
      if (this.thinkingInterval) {
        clearInterval(this.thinkingInterval)
        this.thinkingInterval = null
      }
    },
    toggleQuestionType(type) {
      if (this.paperConfig.questionTypes[type] > 0) {
        this.$set(this.paperConfig.questionTypes, type, 0)
      } else {
        this.$set(this.paperConfig.questionTypes, type, 1)
      }
    },
    adjustTypeCount(type, delta) {
      const newValue = this.paperConfig.questionTypes[type] + delta
      if (newValue >= 0) {
        this.$set(this.paperConfig.questionTypes, type, newValue)
      }
    },
    validateTypeScore(type) {
      if (this.typeScores[type] < 1) {
        this.typeScores[type] = 1
      }
    },
    // 检查题型数量是否超出题库总量
    validateQuestionTypeNumbers() {
      // 如果没有选择题库或不是基于题库出卷模式，跳过验证
      if (this.activeMode !== 'existing' || this.selectedBanks.length === 0) {
        return { valid: true };
      }

      // 计算所有选中题库的各题型总量
      const typeTotals = {
        single: 0,   // 单选题
        multiple: 0,  // 多选题
        truefalse: 0, // 判断题
        fillblank: 0, // 填空题
        essay: 0      // 简答题
      };

      // 遍历所有选中的题库，累加各题型数量
      this.selectedBankDetails.forEach(bank => {
        // 单选题
        typeTotals.single += (bank.choiceNum || bank.questionBank?.choiceNum || 0);
        // 多选题
        typeTotals.multiple += (bank.choicesNum || bank.questionBank?.choicesNum || 0);
        // 判断题
        typeTotals.truefalse += (bank.judgementNum || bank.questionBank?.judgementNum || 0);
        // 填空题
        typeTotals.fillblank += (bank.vacancyNum || bank.questionBank?.vacancyNum || 0);
        // 简答题
        typeTotals.essay += (bank.shortNum || bank.questionBank?.shortNum || 0);
      });

      // 检查每种题型是否超出数量限制
      const typeNameMap = {
        single: '单选题',
        multiple: '多选题',
        truefalse: '判断题',
        fillblank: '填空题',
        essay: '简答题'
      };

      // 检查是否有题型超出

      let typeName = "";
      let msg = "超出题库中可用数量";
      let flag = true;
      for (const type in this.paperConfig.questionTypes) {
        const configCount = this.paperConfig.questionTypes[type];
        const availableCount = typeTotals[type];

        if (configCount > 0 && configCount > availableCount) {
          typeName += ` ${typeNameMap[type]},`;
          flag = false;
        }
      }

      if (!flag) {


        return {
          valid: flag,
          message: `${typeName}${msg}`
        }
      }

      return { valid: flag };
    },
    async generatePaper() {
      // 验证题型数量是否超出选中题库中的总数量
      const validationResult = this.validateQuestionTypeNumbers();

      if (!validationResult.valid) {
        this.$message.error(validationResult.message);
        return;
      }

      this.generating = true
      this.generationProgress = 0
      this.generatedPaper = []
      this.showAnalysis = {}

      // 启动思考动画
      this.startThinkingAnimation()

      // 启动进度自动更新
      this.startProgressAnimation()

      let param = {
        paperName: this.paperConfig.name, // 试卷名称
        timeLimit: this.paperConfig.duration, // 考试时长
        bankIds: this.selectedBanks, // 题库ID列表
        questionTypeNumVO: { // 题型数量分数配置
          choiceNum: this.paperConfig.questionTypes.single, // 单选题数量
          choiceScore: this.typeScores.single, // 单选题分数
          choicesNum: this.paperConfig.questionTypes.multiple, // 多选题数量
          choicesScore: this.typeScores.multiple,   // 多选题分数
          vacancyNum: this.paperConfig.questionTypes.fillblank,  // 填空题数量
          vacancyScore: this.typeScores.fillblank, // 填空题分数
          shortNum: this.paperConfig.questionTypes.essay, // 简答题数量
          shortScore: this.typeScores.essay, // 简答题分数
          judgementNum: this.paperConfig.questionTypes.truefalse, // 判断题数量
          judgementScore: this.typeScores.truefalse // 判断题分数
        }
      }

      try {
        let res = await createPaperWithQuestionsAPI(param);
        let { data } = res.data;

        if (data == null) {
          this.$message.error('试卷生成失败，请检查题库配置或稍后再试');
          this.generating = false;
          this.stopAnimations();
          return;
        }

        // 保存返回的数据，但不立即展示
        this.generatePaperId = data.paperId; // 生成的试卷ID
        this.paperQuestions = data.questions; // 试卷题目

        // 如果API响应很快，确保至少完成到第3步
        if (this.generationProgress < 3) {
          this.generationProgress = 3;
        }

        // 等待进度走完再显示结果
        this.completeProgressAnimation().then(() => {
          // 设置生成成功标记
          this.paperGenerated = true;
          this.generating = false;
          this.stopAnimations();
        });

      } catch (error) {
        this.$message.error(error)
        this.generating = false;
        this.stopAnimations();
      }
    },

    // 启动进度自动更新
    startProgressAnimation() {
      // 清除可能存在的定时器
      this.stopProgressTimer();

      // 存储步骤时间和总时间
      const totalSteps = 5;
      // 延长每个步骤的时间，让整个过程更加缓慢
      const stepTimes = [3000, 3500, 4000, 3800, 3500]; // 每一步的时间，单位ms

      // 创建一个递增进度的函数
      const advanceProgress = (step) => {
        if (step < totalSteps && this.generating) {
          this.generationProgress = step;

          // 设置下一步的定时器
          this.progressTimer = setTimeout(() => {
            advanceProgress(step + 1);
          }, stepTimes[step]);
        }
      };

      // 开始进度动画
      advanceProgress(0);
    },

    // 停止进度定时器
    stopProgressTimer() {
      if (this.progressTimer) {
        clearTimeout(this.progressTimer);
        this.progressTimer = null;
      }
    },

    // 完成所有进度
    async completeProgressAnimation() {
      return new Promise(resolve => {
        // 停止现有定时器
        this.stopProgressTimer();

        // 如果API响应很快，确保至少从第一步开始显示
        if (this.generationProgress > 0) {
          this.generationProgress = 0;
        }

        // 每一步完成的时间间隔（单位：毫秒）
        const stepInterval = 1500;

        // 逐步显示每个完成状态
        const advanceCompletedStep = (step) => {
          this.generationProgress = step;

          if (step < 4) {
            // 等待一段时间后显示下一个完成状态
            setTimeout(() => {
              advanceCompletedStep(step + 1);
            }, stepInterval);
          } else {
            // 最后一步完成后等待一会再关闭
            setTimeout(() => {
              resolve();
            }, 2000);
          }
        };

        // 开始从第一步展示完成状态
        advanceCompletedStep(0);
      });
    },

    // 停止所有动画
    stopAnimations() {
      this.stopThinkingAnimation();
      this.stopProgressTimer();
    },
    generationComplete() {
      this.generating = false
      // 确保生成所有题目
      this.generateQuestionsBatch(true)

      // 为所有题目初始化显示解析状态
      this.generatedPaper.forEach(q => {
        this.$set(this.showAnalysis, q.id, false)
      })
    },
    generateQuestionsBatch(forceComplete = false) {
      const batchSize = forceComplete ? this.totalQuestions : Math.min(3, this.totalQuestions - this.generatedPaper.length)

      for (let i = 0; i < batchSize; i++) {
        const type = this.getRandomQuestionType()
        this.generatedPaper.push(this.generateQuestion(type))
      }
    },
    getRandomQuestionType() {
      const types = []
      for (const type in this.paperConfig.questionTypes) {
        if (this.paperConfig.questionTypes[type] > 0) {
          // 根据配置的数量比例添加类型
          for (let i = 0; i < this.paperConfig.questionTypes[type]; i++) {
            types.push(type)
          }
        }
      }
      return types[Math.floor(Math.random() * types.length)]
    },
    generateQuestion(type) {
      const id = `q-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      const baseQuestion = {
        id,
        type,
        content: this.generateQuestionContent(type),
        difficulty: this.getRandomDifficulty(),
        correct_answer: this.generateCorrectAnswer(type),
        options: type === 'fillblank' || type === 'essay' ? null : this.generateOptions(type),
        analysis: this.generateAnalysis(type),
        knowledge_points: this.generateKnowledgePoints(),
        parse: '这是题目的答案解析...'
      }

      return baseQuestion
    },
    generateQuestionContent(type) {
      const topics = {
        single: [
          '关于%s的描述中，哪一项是正确的？',
          '在%s中，以下哪种做法是最佳实践？',
          '关于%s的实现方式，以下说法错误的是？'
        ],
        multiple: [
          '关于%s，以下哪些说法是正确的？',
          '在%s场景中，以下哪些做法是合适的？',
          '以下哪些选项描述了%s的正确特性？'
        ],
        truefalse: [
          '判断: %s的描述是否正确？',
          '以下关于%s的说法是否正确？',
          '判断正误: %s'
        ],
        fillblank: [
          '请填写%s中的空白处: _____',
          '在%s中，缺失的部分是: _____',
          '完成%s的表述: _____'
        ],
        essay: [
          '请简要说明%s的主要特点和优势',
          '论述%s在实际应用中的场景和注意事项',
          '比较%s和%s的异同点'
        ]
      }

      const keyword = this.activeMode === 'aiPanel'
        ? this.aiConfig.keywords.split('、')[0] || '相关知识点'
        : '题库知识点'

      const template = topics[type][Math.floor(Math.random() * topics[type].length)]

      // 简答题可能需要两个关键词
      if (type === 'essay' && this.aiConfig.keywords.split('、').length > 1) {
        const keywords = this.aiConfig.keywords.split('、')
        return template.replace('%s', keywords[0]).replace('%s', keywords[1])
      }

      return template.replace('%s', keyword)
    },
    generateOptions(type) {
      const count = type === 'multiple' ? 4 : type === 'truefalse' ? 2 : 4
      const options = []

      for (let i = 0; i < count; i++) {
        const letter = String.fromCharCode(65 + i)
        options.push(`${letter}. ${this.generateOptionText(type)}`)
      }

      return options.join('\n')
    },
    generateOptionText() {
      const texts = [
        '正确选项描述',
        '常见错误描述',
        '部分正确但不完全',
        '完全错误的描述',
        '特殊情况下的表现',
        '理论上的最佳实践'
      ]
      return texts[Math.floor(Math.random() * texts.length)]
    },
    generateCorrectAnswer(type) {
      switch (type) {
        case 'single':
          return ['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)]
        case 'multiple':
          return ['A', 'B', 'C', 'D']
            .slice(0, 2 + Math.floor(Math.random() * 2))
            .sort()
            .join('')
        case 'truefalse':
          return Math.random() > 0.5 ? 'A' : 'B'
        case 'fillblank':
          return '正确答案'
        case 'essay':
          return '这是简答题的参考答案。在实际应用中，应该根据题目要求提供详细、准确的回答。参考答案通常包括关键点、示例和必要的解释。'
      }
    },
    generateAnalysis() {
      const analyses = [
        '本题考查了核心知识点，正确答案的关键在于理解基本概念。',
        '此题容易混淆，需要注意区分相似概念的不同之处。',
        '正确答案的选择基于对基本原理的掌握，错误选项是常见的误解。',
        '本题考察综合应用能力，需要将多个知识点结合起来分析。',
        '解题时需要特别注意题目中的关键词，它们往往是解题的突破口。'
      ]
      return analyses[Math.floor(Math.random() * analyses.length)]
    },
    generateKnowledgePoints() {
      const points = [
        '面向对象编程、封装、继承、多态',
        '数据库索引、事务、锁机制',
        '进程调度、内存管理、文件系统',
        'TCP/IP协议、HTTP协议、网络安全',
        '算法复杂度、数据结构、设计模式'
      ]
      return points[Math.floor(Math.random() * points.length)]
    },
    getRandomDifficulty() {
      const rand = Math.random() * 100
      if (rand < this.paperConfig.difficultyDistribution.easy) return 'easy'
      if (rand < this.paperConfig.difficultyDistribution.easy + this.paperConfig.difficultyDistribution.medium) return 'medium'
      return 'hard'
    },
    resetConfig() {
      this.paperConfig = {
        name: '',
        totalScore: 100,
        duration: 90,
        coverage: 70,
        questionTypes: {
          single: 5,
          multiple: 3,
          truefalse: 2,
          fillblank: 0,
          essay: 1
        },
        difficultyDistribution: {
          easy: 20,
          medium: 60,
          hard: 20
        }
      }
      this.aiConfig = {
        keywords: '',
        style: 'exam',
        intelligence: 3
      }
      this.selectedBanks = []
      this.generatedPaper = []
      this.paperGenerated = false
      this.generatePaperId = 0
    },
  },
  beforeDestroy() {
    this.stopAnimations();
  },
  watch: {
    'paperConfig.name'(newName) {
      if (this.isDuplicatePaperName) {
        this.$message.error('试卷名称已存在，请重新命名')
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/styles/variables.less";

/* 新增的题型配置头部样式 */
/* 删除不再使用的section-header-flex相关样式 */

/* 题库选择区域样式 */
.selected-banks-container {
  margin-top: 0.5rem;
}

.selected-banks {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  align-items: center;
  min-height: 48px;

  .bank-tag {
    display: flex;
    align-items: center;
    background: white;
    border-radius: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border: 1px solid @gray-200;
    transition: all 0.2s ease;
    overflow: hidden;

    &:hover {
      border-color: @primary-light;
      box-shadow: 0 2px 6px rgba(@primary, 0.1);
    }

    .bank-tag-content {
      padding: 0.5rem 0.75rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;

      .bank-name {
        font-size: 0.8125rem;
        font-weight: 500;
        color: @gray-800;
      }

      .question-count {
        font-size: 0.75rem;
        color: @gray-500;
        background: @gray-100;
        padding: 0.125rem 0.375rem;
        border-radius: 10px;
      }
    }

    .remove-bank {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: @gray-100;
      color: @gray-600;
      border: none;
      border-left: 1px solid @gray-200;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background: @error-light;
        color: @error;
      }

      i {
        font-size: 0.8rem;
      }
    }
  }

  .btn-add-bank {
    padding: 0.5rem 1rem;
    border-radius: 24px;
    background: white;
    border: 1px dashed @primary;
    color: @primary;
    font-size: 0.8125rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background: rgba(@primary, 0.05);
      border-style: solid;
    }

    i {
      font-size: 0.8rem;
    }
  }
}

.bank-selection-hint {
  margin-top: 0.75rem;
  padding: 0.75rem;
  background: rgba(@primary, 0.05);
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8125rem;
  color: @primary;

  i {
    font-size: 0.9rem;
  }
}

/* 模态框中的题库卡片样式 */
.bank-selection {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 1rem;
  max-height: 300px;
  overflow-y: auto;
  padding: 0.5rem;
  margin-top: 0.5rem;

  .bank-card {
    padding: 1rem;
    border-radius: 12px;
    border: 1px solid @gray-200;
    cursor: pointer;
    transition: all 0.2s ease;
    background: white;
    position: relative;
    overflow: hidden;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
      border-color: @primary-light;
    }

    &.selected {
      border-color: @primary;
      background: rgba(@primary, 0.03);
      box-shadow: 0 0 0 2px rgba(@primary, 0.2);

      &::after {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 24px;
        height: 24px;
        background: @primary;
        clip-path: polygon(100% 0, 0 0, 100% 100%);
      }

      &::before {
        content: '\f00c';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        position: absolute;
        top: 2px;
        right: 2px;
        color: white;
        font-size: 0.6rem;
        z-index: 1;
      }

      .bank-icon {
        background: @primary;
        color: white;
      }
    }

    .bank-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      background: @gray-100;
      display: flex;
      align-items: center;
      justify-content: center;
      color: @gray-600;
      margin-bottom: 0.75rem;
      transition: all 0.2s ease;
      font-size: 1.5rem;
    }

    .bank-info {
      h4 {
        margin: 0;
        font-size: 0.9375rem;
        color: @gray-800;
        font-weight: 600;
        line-height: 1.3;
      }

      p {
        margin: 0.25rem 0 0;
        font-size: 0.8125rem;
        color: @gray-500;
      }

      .bank-tags {
        margin-top: 0.75rem;
        display: flex;
        flex-wrap: wrap;
        gap: 0.375rem;

        .tag {
          font-size: 0.6875rem;
          padding: 0.25rem 0.5rem;
          background: @gray-100;
          border-radius: 4px;
          color: @gray-600;
          transition: all 0.2s ease;

          &:hover {
            background: @primary-light;
            color: @primary;
          }
        }
      }
    }
  }
}

.ai-paper-generator-box {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 1200px;
  height: 80vh;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  animation: dialogEnter 0.3s ease-out;
  overflow: hidden;
  transition: all 0.3s ease;

  &.fullscreen {
    width: 100%;
    height: 100vh;
    max-width: none;
    border-radius: 0;
  }
}

.generator-header {
  padding: 1rem 1.5rem;
  background: linear-gradient(135deg, #4361EE, #3A0CA3);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: flex-end;
    gap: 1.5rem;

    h2 {
      margin: 0;
      font-size: 1.25rem;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 0.5rem;

      i {
        font-size: 1.2em;
      }
    }

    .mode-tabs {
      display: flex;
      gap: 0.5rem;

      button {
        padding: 0.5rem 1rem;
        border-radius: 20px;
        border: none;
        background: rgba(255, 255, 255, 0.1);
        color: white;
        font-size: 0.875rem;
        cursor: pointer;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        gap: 0.5rem;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }

        &.active {
          background: white;
          color: #4361EE;
          font-weight: 500;
        }

        i {
          font-size: 0.9em;
        }
      }
    }
  }

  .header-right {
    display: flex;
    gap: 0.75rem;
    align-items: center;

    .btn-save {
      padding: 0.5rem 1rem;
      border-radius: 20px;
      background: rgba(255, 255, 255, 0.2);
      color: white;
      border: none;
      font-size: 0.875rem;
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      gap: 0.5rem;

      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }

      i {
        font-size: 0.9em;
      }
    }

    .btn-icon {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      border: none;
      color: white;
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(255, 255, 255, 0.2);
      }

      &.btn-close:hover {
        background: rgba(239, 68, 68, 0.7);
      }

      i {
        font-size: 1rem;
      }
    }
  }
}

.generator-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.config-panel {
  width: 380px;
  padding: 1.5rem;
  border-right: 1px solid @gray-200;
  overflow-y: auto;
  background: white;

  .panel-section {
    margin-bottom: 1.5rem;

    h3 {
      font-size: 0.9375rem;
      color: @gray-700;
      margin: 0 0 1rem 0;
      display: flex;
      align-items: center;
      gap: 0.5rem;

      i {
        color: @primary;
      }
    }
  }

  .form-group {
    margin-bottom: 1rem;

    .paper-name-red {
      border-color: @error;
    }

    label {
      display: block;
      margin-bottom: 0.5rem;
      font-size: 0.875rem;
      font-weight: 500;
      color: @gray-700;
    }

    input,
    textarea,
    select {
      width: 100%;
      padding: 0.75rem;
      border: 1px solid @gray-300;
      border-radius: 8px;
      font-size: 0.875rem;
      transition: all 0.2s ease;
      background-color: @gray-50;

      &:focus {
        outline: none;
        border-color: @primary;
        box-shadow: 0 0 0 3px rgba(@primary, 0.1);
        background-color: white;
      }
    }

    textarea {
      resize: vertical;
      min-height: 80px;
    }
  }

  .ai-intelligence {
    margin-top: 0.5rem;

    input[type="range"] {
      width: 100%;
      height: 6px;
      -webkit-appearance: none;
      background: @gray-200;
      border-radius: 3px;
      outline: none;
      margin-bottom: 0.5rem;

      &::-webkit-slider-thumb {
        -webkit-appearance: none;
        width: 18px;
        height: 18px;
        background: @primary;
        border-radius: 50%;
        cursor: pointer;
      }
    }

    .intensity-labels {
      display: flex;
      justify-content: space-between;

      span {
        color: @gray-500;
        font-size: 0.75rem;

        &.active {
          color: @primary;
        }

        i {
          font-size: 1rem;
        }
      }
    }
  }

  .form-row {
    display: flex;
    gap: 1rem;

    .form-group {
      flex: 1;
    }
  }

  .bank-selection {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 0.75rem;
    max-height: 200px;
    overflow-y: auto;
    padding: 0.25rem;

    .bank-card {
      padding: 0.75rem;
      border-radius: 8px;
      border: 1px solid @gray-200;
      cursor: pointer;
      transition: all 0.2s ease;
      background: white;

      &:hover {
        border-color: @primary-light;
      }

      &.selected {
        border-color: @primary;
        background: rgba(@primary, 0.05);

        .bank-icon {
          background: @primary;
          color: white;
        }
      }

      .bank-icon {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        background: @gray-100;
        display: flex;
        align-items: center;
        justify-content: center;
        color: @gray-600;
        margin-bottom: 0.5rem;
        transition: all 0.2s ease;

        i {
          font-size: 1.25rem;
        }
      }

      .bank-info {
        h4 {
          margin: 0;
          font-size: 0.875rem;
          color: @gray-800;
        }

        p {
          margin: 0.25rem 0 0;
          font-size: 0.75rem;
          color: @gray-500;
        }

        .bank-tags {
          margin-top: 0.5rem;
          display: flex;
          flex-wrap: wrap;
          gap: 0.25rem;

          .tag {
            font-size: 0.625rem;
            padding: 0.125rem 0.375rem;
            background: @gray-100;
            border-radius: 4px;
            color: @gray-600;
          }
        }
      }
    }
  }

  .question-type-config {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.75rem;

    .type-card {
      border-radius: 8px;
      border: 1px solid @gray-200;
      overflow: hidden;
      transition: all 0.2s ease;

      &.active {
        border-color: @primary;
        box-shadow: 0 1px 3px rgba(@primary, 0.1);
      }

      .type-header {
        padding: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        cursor: pointer;
        background: white;
        position: relative;

        .type-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          flex-shrink: 0;

          i {
            font-size: 1.25rem;
          }
        }

        .type-info {
          flex: 1;

          h4 {
            margin: 0;
            font-size: 0.875rem;
            color: @gray-800;
          }

          p {
            margin: 0.25rem 0 0;
            font-size: 0.75rem;
            color: @gray-500;
          }
        }

        .type-badge {
          position: absolute;
          top: -1px;
          right: -1px;
          background: @primary;
          color: white;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 0.75rem;
          font-weight: bold;
        }
      }

      .type-controls {
        padding: 0.75rem;
        background: @gray-50;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;

        .type-score-control {
          flex: 0 0 auto;
          display: flex;
          align-items: center;
          gap: 0.5rem;
          background: white;
          padding: 0.375rem 0.75rem;
          border-radius: 20px;
          border: 1px solid @gray-200;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

          label {
            font-size: 0.75rem;
            color: @gray-700;
            white-space: nowrap;
            margin-bottom: 0;
            font-weight: 500;
          }

          input {
            width: 40px;
            padding: 0.25rem;
            border: none;
            border-radius: 4px;
            text-align: center;
            font-size: 0.875rem;
            background: transparent;
            color: @primary;
            font-weight: 600;

            &:focus {
              outline: none;
              background-color: @gray-50;
            }

            &::-webkit-inner-spin-button,
            &::-webkit-outer-spin-button {
              opacity: 0;
              height: 1.5em;
              width: 1.5em;
              margin-right: -0.75em;
              position: relative;
              z-index: 2;
            }
          }
        }

        .type-count-control {
          display: flex;
          align-items: center;
          background: white;
          padding: 0.25rem;
          border-radius: 20px;
          border: 1px solid @gray-200;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

          .btn-count {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            border: none;
            background: @gray-100;
            color: @primary;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover {
              background: @primary-light;
              color: darken(@primary, 10%);
              transform: scale(1.05);
            }

            &:first-child {
              color: #e63946;

              &:hover {
                background: rgba(#e63946, 0.1);
                color: darken(#e63946, 10%);
              }
            }

            &:last-child {
              color: #2a9d8f;

              &:hover {
                background: rgba(#2a9d8f, 0.1);
                color: darken(#2a9d8f, 10%);
              }
            }

            i {
              font-size: 1rem;
            }
          }

          .count-display {
            min-width: 30px;
            text-align: center;
            font-weight: 600;
            color: @gray-800;
            font-size: 0.9rem;
          }
        }
      }
    }
  }

  .difficulty-distribution {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0.75rem;

    .difficulty-item {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      font-size: 0.875rem;
      color: @gray-700;

      input {
        width: 60px;
        padding: 0.5rem;
        border: 1px solid @gray-300;
        border-radius: 4px;
        text-align: center;
      }
    }
  }

  .difficulty-preview {
    height: 6px;
    background: @gray-200;
    border-radius: 3px;
    margin-top: 0.5rem;
    display: flex;
    overflow: hidden;

    .difficulty-bar {
      height: 100%;
      transition: width 0.3s ease;
    }
  }

  .coverage-control {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-top: 0.5rem;

    input[type="range"] {
      flex: 1;
      height: 6px;
      -webkit-appearance: none;
      background: @gray-200;
      border-radius: 3px;
      outline: none;

      &::-webkit-slider-thumb {
        -webkit-appearance: none;
        width: 16px;
        height: 16px;
        background: @primary;
        border-radius: 50%;
        cursor: pointer;
      }
    }

    span {
      font-size: 0.875rem;
      color: @gray-700;
      min-width: 40px;
      text-align: right;
    }
  }

  .total-count {
    margin-top: 1rem;
    margin: 0 0 1rem 0;
    padding-top: 0;
    border-top: none;
    text-align: center;
    font-size: 0.875rem;
    color: @gray-700;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;

    strong {
      color: @primary;
      font-weight: 600;
    }

    .score-match {
      margin-left: 0.5rem;
      font-size: 0.75rem;
      padding: 0.125rem 0.5rem;
      border-radius: 10px;
      background: @success-light;
      color: @success;

      &.match-error {
        background: @error-light;
        color: @error;
      }

      i {
        margin-right: 0.25rem;
      }
    }
  }

  /* 题型配置内的总分计数 */
  /* 删除不再使用的section-header-flex的total-count样式 */


}

.action-buttons {
  display: flex;
  gap: 1rem;
  padding: 0.8rem 1.5rem;
  background: white;
  border-top: 1px solid @gray-200;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  position: sticky;
  bottom: 0;
  z-index: 10;
  width: 100%;
  margin-top: auto;
  justify-content: flex-end;

  .generation-hint {
    background: rgba(@warning, 0.1);
    color: @warning;
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-size: 0.875rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-right: auto;
    border-left: 3px solid @warning;

    i {
      font-size: 1rem;
    }
  }

  button {
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    font-size: 0.9375rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all 0.2s ease;
    flex: 0 0 auto;
    min-width: 120px;
  }

  .btn-generate {
    background: linear-gradient(135deg, @primary, darken(@primary, 15%));
    color: white;
    box-shadow: 0 2px 8px rgba(@primary, 0.3);
    position: relative;
    overflow: hidden;

    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.2));
      opacity: 0;
      transition: all 0.2s ease;
    }

    &:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(@primary, 0.4);

      &::after {
        opacity: 1;
      }
    }

    &:disabled {
      background: linear-gradient(135deg, lighten(@primary, 20%), lighten(@primary, 10%));
      cursor: not-allowed;
    }
  }

  .btn-reset {
    background: @gray-100;
    color: @gray-700;
    border: 1px solid @gray-300;

    &:hover {
      background: @gray-200;
      transform: translateY(-2px);
    }
  }

  // 响应式调整
  @media (max-width: 768px) {
    padding: 0.75rem 1rem;
    flex-wrap: wrap;
    justify-content: flex-end;
    gap: 0.75rem;

    button {
      flex: 0 0 auto;
      min-width: 120px;
      padding: 0.75rem 1rem;
      font-size: 0.875rem;
    }

    .generation-hint {
      width: 100%;
      margin-bottom: 0.75rem;
      font-size: 0.8125rem;
      padding: 0.375rem 0.75rem;
    }
  }

  @media (max-width: 480px) {
    gap: 0.5rem;

    button {
      min-width: 100px;
    }
  }
}

.preview-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: @gray-50;

  .waiting-paper {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 242, 255, 0.95) 100%);

    .loader-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;

      .paper-loader {
        position: relative;
        width: 80px;
        height: 80px;
        background-color: @primary;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 0 20px rgba(@primary, 0.4);
        animation: pulse-glow 2s infinite ease-in-out;

        &:before {
          content: '\f2db';
          font-family: 'Font Awesome 5 Free';
          font-weight: 900;
          color: white;
          font-size: 32px;
        }

        &:after {
          content: '';
          position: absolute;
          width: 100%;
          height: 100%;
          border-radius: 50%;
          border: 3px solid rgba(@primary, 0.6);
          animation: ripple 1.5s infinite;
        }
      }

      p {
        margin-top: 2rem;
        color: @primary;
        font-weight: 500;
        font-size: 1.25rem;
      }

      .thinking-dots {
        display: flex;
        gap: 6px;
        margin-top: 1rem;

        .dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: @primary;

          &:nth-child(1) {
            animation: dot-bounce 1.4s -0.32s infinite ease-in-out;
          }

          &:nth-child(2) {
            animation: dot-bounce 1.4s -0.16s infinite ease-in-out;
          }

          &:nth-child(3) {
            animation: dot-bounce 1.4s 0s infinite ease-in-out;
          }
        }
      }

      .generation-status {
        margin-top: 2rem;
        max-width: 400px;
        padding: 1rem;
        background-color: rgba(255, 255, 255, 0.7);
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

        .status-title {
          font-weight: 600;
          margin-bottom: 0.5rem;
          color: @gray-800;
          font-size: 0.9rem;
        }

        .status-list {
          text-align: left;

          .status-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 0;
            color: @gray-600;
            font-size: 0.85rem;

            i {
              color: @primary;
            }

            &.active {
              color: @primary;
              font-weight: 500;
            }

            &.completed {
              color: @success;

              i {
                color: @success;
              }
            }
          }
        }
      }
    }

    @keyframes pulse-glow {
      0% {
        box-shadow: 0 0 15px rgba(@primary, 0.4);
        transform: scale(0.95);
      }

      50% {
        box-shadow: 0 0 25px rgba(@primary, 0.6);
        transform: scale(1);
      }

      100% {
        box-shadow: 0 0 15px rgba(@primary, 0.4);
        transform: scale(0.95);
      }
    }

    @keyframes ripple {
      0% {
        transform: scale(1);
        opacity: 1;
      }

      100% {
        transform: scale(1.4);
        opacity: 0;
      }
    }

    @keyframes dot-bounce {

      0%,
      80%,
      100% {
        transform: translateY(0);
      }

      40% {
        transform: translateY(-10px);
      }
    }
  }

  .empty-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: @gray-700;
    text-align: center;
    padding: 1.5rem;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(240, 242, 255, 0.9) 100%);

    .ai-robot-icon {
      font-size: 3.5rem;
      margin-bottom: 1rem;
      color: @primary;
      animation: pulse 2s infinite alternate;
    }

    .preview-title {
      font-size: 1.5rem;
      font-weight: 600;
      margin-bottom: 0.5rem;
      color: @gray-800;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .preview-desc {
      font-size: 1rem;
      margin-bottom: 1.5rem;
      color: @gray-600;
    }

    .preview-features {
      display: flex;
      justify-content: center;
      gap: 1.5rem;
      margin-bottom: 1.5rem;

      .feature-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.5rem;

        i {
          font-size: 1.25rem;
          color: @primary;
          padding: 0.75rem;
          background: rgba(@primary, 0.1);
          border-radius: 50%;
        }

        span {
          font-weight: 500;
          font-size: 0.875rem;
          color: @gray-700;
        }
      }
    }

    .preview-note {
      padding: 0.75rem 1rem;
      background: rgba(@warning, 0.1);
      border-left: 4px solid @warning;
      border-radius: 4px;
      display: flex;
      align-items: center;
      gap: 0.75rem;
      max-width: 400px;

      i {
        font-size: 1.25rem;
        color: @warning;
      }

      p {
        color: @gray-700;
        font-size: 0.875rem;
        margin: 0;
      }
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  100% {
    transform: scale(1.1);
  }
}

@media (max-width: 1200px) {
  .generator-main {
    flex-direction: column;
  }

  .config-panel {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid @gray-200;
  }

  .bank-selection {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)) !important;
  }
}

@media (max-width: 768px) {
  .generator-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
    padding: 1rem;

    .header-left {
      flex-direction: column;
      align-items: flex-start;
      gap: 0.75rem;
      width: 100%;

      .mode-tabs {
        width: 100%;
        overflow-x: auto;
        padding-bottom: 0.5rem;
      }
    }

    .header-right {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .difficulty-distribution {
    grid-template-columns: 1fr !important;
  }

  .question-type-config {
    grid-template-columns: repeat(2, 1fr) !important;
  }

  /* 调整小屏幕下的section-header */
  .section-header {
    flex-wrap: wrap;
    gap: 0.5rem;
    align-items: flex-end;
    /* 保持底部对齐 */

    .header-left {
      margin-bottom: 0.5rem;
    }

    .total-count {
      margin-bottom: 0.5rem;
      width: auto;
      justify-content: flex-end;
    }
  }
}

@media (max-width: 480px) {
  .question-type-config {
    grid-template-columns: 1fr !important;
  }

  .action-buttons {
    flex-direction: column;
  }

  .preview-actions {
    flex-direction: column;
    align-items: flex-end;

    button {
      width: 100%;
      justify-content: center;
    }
  }

  .question-actions {
    flex-direction: column;

    button {
      width: 100%;
      justify-content: center;
    }
  }
}

.section-header {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-bottom: 0.75rem;
  position: relative;
  border-bottom: 1px solid @gray-200;
  padding-bottom: 0.5rem;

  .header-left {
    display: flex;
    align-items: flex-end;
    gap: 0.75rem;
  }

  i {
    color: @primary;
    font-size: 1.1rem;
  }

  h3 {
    margin: 0;
    font-size: 1rem;
    color: @gray-800;
    font-weight: 600;
    line-height: 1.5;
  }

  .total-count {
    font-size: 0.875rem;
    color: @gray-600;
    display: flex;
    align-items: center;
    gap: 0.3rem;
    background-color: @gray-50;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
    white-space: nowrap;
    line-height: 1.5;

    strong {
      color: @primary;
      font-weight: 600;
      margin: 0 2px;
    }
  }
}
</style>